//https://leetcode.cn/problems/reverse-string-ii/
package codeRandomThoughts.Test541反转字符串II;

public class Solution2 {
    public String reverseStr(String s, int k) {
        char[] str = s.toCharArray();
        int i = 0;
        while (i < str.length) {
            int leftChars = str.length - i - 1;
            if (leftChars < k) {
                //如果剩余字符少于k个
                myReverse(str, i, str.length - 1);
            } else {
                //其他任何情况都是反转前k个字符就行
                myReverse(str, i, i + k - 1);
            }

            i += (2 * k);
        }

        return new String(str);
    }

    public void myReverse(char[] str, int begin, int end) {
        char tem;
        //左闭右闭
        while (begin < end) {
            tem = str[begin];
            str[begin] = str[end];
            str[end] = tem;
            begin++;
            end--;
        }
    }
}
